import React, { useState } from 'react';
import {
  Button,
  TextField,
  Box,
  Typography,
  Paper,
  CircularProgress,
  Alert,
} from '@mui/material';
import { CloudUpload as CloudUploadIcon } from '@mui/icons-material';

interface UploadResponse {
  resourceId: number;
  viewUrl: string;
  message: string;
}

const ResourceUploader: React.FC = () => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [file, setFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<UploadResponse | null>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      setFile(event.target.files[0]);
    }
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (!file) {
      setError('请选择要上传的种子文件');
      return;
    }

    try {
      setUploading(true);
      setError(null);
      setSuccess(null);

      // 创建FormData对象
      const formData = new FormData();
      formData.append('title', title);
      formData.append('description', description);
      formData.append('file', file);

      // 发送请求到后端API
      const response = await fetch('http://localhost:8080/api/resource/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
        },
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || '上传失败');
      }

      const result = await response.json();
      setSuccess(result);
      
      // 清空表单
      setTitle('');
      setDescription('');
      setFile(null);
      
      // 重置文件输入框
      const fileInput = document.getElementById('torrent-upload') as HTMLInputElement;
      if (fileInput) {
        fileInput.value = '';
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传过程中发生错误');
    } finally {
      setUploading(false);
    }
  };

  return (
    <Paper elevation={3} sx={{ p: 3, maxWidth: 600, mx: 'auto', mt: 4 }}>
      <Typography variant="h5" component="h2" gutterBottom>
        资源上传
      </Typography>
      
      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      
      {success && (
        <Alert severity="success" sx={{ mb: 2 }}>
          {success.message} - 资源ID: {success.resourceId}
        </Alert>
      )}
      
      <Box component="form" onSubmit={handleSubmit} noValidate>
        <TextField
          margin="normal"
          required
          fullWidth
          label="资源标题"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          disabled={uploading}
        />
        
        <TextField
          margin="normal"
          required
          fullWidth
          label="资源描述"
          multiline
          rows={4}
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          disabled={uploading}
        />
        
        <Box
          sx={{
            mt: 2,
            p: 2,
            border: '2px dashed #ccc',
            borderRadius: 1,
            textAlign: 'center',
            cursor: 'pointer',
            '&:hover': {
              borderColor: 'primary.main',
            },
          }}
          onClick={() => document.getElementById('torrent-upload')?.click()}
        >
          <CloudUploadIcon sx={{ fontSize: 40, color: 'text.secondary' }} />
          <Typography variant="body2" color="text.secondary">
            {file ? file.name : '点击上传种子文件'}
          </Typography>
          <input
            type="file"
            id="torrent-upload"
            hidden
            accept=".torrent"
            onChange={handleFileChange}
            disabled={uploading}
          />
        </Box>
        
        <Button
          type="submit"
          fullWidth
          variant="contained"
          sx={{ mt: 3 }}
          disabled={uploading || !title || !description || !file}
          startIcon={uploading ? <CircularProgress size={20} /> : undefined}
        >
          {uploading ? '上传中...' : '上传资源'}
        </Button>
      </Box>
    </Paper>
  );
};

export default ResourceUploader;